<?php
class CUser extends CRecord {
	static $current = false;
	static $all_privileges = false;
	public $module_privileges = array();
	public $privileges = array();
	public $store;
	public $email;

	/**
	 * Constructor
	 *
	 * @param mixed $data
	 */
	function __construct($data) {
		if(is_array($data) or is_object($data)) {
			parent::__construct($data);
		} else {
			$this->id = $data;
		  if ($ret = @session('user')) {
		    foreach ($ret as $key=>$value) {
		      $this->$key = $value;
		    }
		    return;
		  } else
			if($user = CTable('user')->select($this->id)) {
				if(DEBUG or !$user['privilege_cache']) {
					$new_record = CUser::update_cache($user['id']);
					$user['privilege_cache'] = $new_record['privilege_cache'];
					$user['privileges'] = $new_record['privileges'];
				}
				eval('$this->module_privileges = '.$user['privilege_cache'].';');
				eval('$this->privileges = '.$user['privileges'].';');

				unset($user['privilege_cache']);
				unset($user['privileges']);
				$this->email = $user['email'];
				unset($user['email']);
				unset($user['password']);
				$user['start_time'] = time();
				parent::__construct($user);
				session('user', $this);
			}
		}

		if($this->is_login() and time() - intval(session('last_online_time'))>(RUN_PROMOTION?240:10))
			$this->update_online_status();
	}

	/**
	 * Update wish list
	 *
	 * @param array $items
	 * @return unknown
	 */
	function wishlist($items = false) {
		if($items !== false) {
			if($this->id) {
				CTable('user')->update(array('wishlist'=>var_export($items,1)), $this->id);
			}
		} else {
			if(isset($this->wishlist) and $this->wishlist) {
				eval('$wishlist = '.$this->wishlist.';');
				return $wishlist;
			}
		}
		return array();
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $items
	 * @return unknown
	 */
	function shopping_cart($items = false) {
		if($items !== false) {
			session('cart', $items);
		} else {
			if($shopping_cart = session('cart')) {
				return $shopping_cart;
			}
		}
		return array();
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $items
	 * @return unknown
	 */
	function widget($items = false) {
		if($items !== false) {
			session('widget', $items);
		} else {
			if($widget = session('widget')) {
				return $widget;
			}
		}
		return array();
	}

	/**
	 * Enter description here...
	 *
	 */
	function shopping_cart_count() {
		return intval(@count(session('cart')));
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $path
	 * @return unknown
	 */
	function table($path) {
		return CTable($path)->change_store($this->store);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $password
	 * @return unknown
	 */
	static function encode_password($password) {
		return md5($password.'vinbuy2008');
	}

	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	function is_login() {
		return session('user_id');
	}

	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	function is_admin() {
        return isset($this->privileges[CPortal::$default]['Administrators']) or
			(isset($this->privileges['default']) && isset($this->privileges['default']['Administrators'])) or
			isset($this->privileges[portal()->id]['Administrators']);
	}

	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	function is_shop_admin() {
		$is_admin=$this->is_admin();
		return $is_admin or isset($this->privileges[CPortal::$default]['ShopAdministrators']) or
				isset($this->privileges['default']['ShopAdministrators']) or
				isset($this->privileges[portal()->id]['ShopAdministrators']);
	}
	function is_game_admin() {
		$is_admin=$this->is_admin();
		return $is_admin or isset($this->privileges[CPortal::$default]['GameAdmin']) or
				isset($this->privileges['default']['GameAdmin']) or
				isset($this->privileges[portal()->id]['GameAdmin']);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $pos
	 * @param unknown_type $module_id
	 * @param unknown_type $parameters
	 * @return unknown
	 */
	function can_do_action($pos,$module_id=false, $parameters = 0) {
		if($this->is_admin()) {
			return true;
		}
		if(!$module_id) {
			if ($module = @module()) {
				$module_id = $module->name;
			} else {
				$module_id=false;
			}
		}

		if(!$module_id) return;
		if(isset($this->module_privileges[CPortal::$current->id])) {
			if(isset($this->module_privileges[CPortal::$current->id][$module_id])) {
				if($this->module_privileges[CPortal::$current->id][$module_id]&(1 << $pos)) {
					return true;
				}
			}
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_view($module_id=false, $category_id = 0) {
		return $this->can_do_action(0,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_view_detail($module_id=false, $category_id = 0) {
		return $this->can_do_action(1,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_add($module_id=false, $category_id = 0) {
		return $this->can_do_action(2,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_edit($module_id=false, $category_id = 0) {
		return $this->can_do_action(3,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_delete($module_id=false, $category_id = 0) {
		return $this->can_do_action(4,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_moderator($module_id=false, $category_id = 0) {
		return $this->can_do_action(5,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_developer($module_id=false, $category_id = 0) {
		return $this->can_do_action(6,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $module_id
	 * @param unknown_type $category_id
	 * @return unknown
	 */
	function can_admin($module_id=false, $category_id = 0) {
		return $this->can_do_action(7,$module_id, $category_id);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $portal_id
	 * @param unknown_type $all_privileges
	 * @param unknown_type $privilege_id
	 * @param unknown_type $values
	 */
	static function get_child_privileges($portal_id, &$all_privileges, $privilege_id, $values) {
		if(!CUser::$all_privileges) {
			CUser::$all_privileges = CTable('privilege')->select_all();
		}
		if($privileges = CList(CUser::$all_privileges)->filter(array('parent_id' => $privilege_id))) {
			foreach($privileges as $privilege) {
				if(!isset($all_privileges[$portal_id][$privilege['id']])) {
					$all_privileges[$portal_id][$privilege['id']] = $values;
					CUser::get_child_privileges($portal_id, $all_privileges, $privilege['id'], $values);
				}
			}
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $user_id
	 * @param unknown_type $all_privileges
	 * @return unknown
	 */
	static function privilege_cache($user_id, &$all_privileges) {
		$privileges = array();
		$all_privileges = array();
		if($user_privileges = CTable('user_privilege')->select_all(array('user_id'=>$user_id))) {
			foreach($user_privileges as $user_privilege) {
				if(!isset($all_privileges[$user_privilege['portal_id']])) {
					$all_privileges[$user_privilege['portal_id']] = array();
				}
				$values = 1;
				if($categories = CTable('privilege_category')->select_all(array(
					'user_id' => $user_id,
					'portal_id' => $user_privilege['portal_id'],
					'privilege_id' => $user_privilege['privilege_id']
				)))
				{
					$values = array();
					foreach($categories as $category) {
						$values[$category['category_id']] = 2;
					}
				}
				$all_privileges[$user_privilege['portal_id']][$user_privilege['privilege_id']] = $values;
				CUser::get_child_privileges($user_privilege['portal_id'], $all_privileges, $user_privilege['privilege_id'], $values);

				if(!isset($privileges[$user_privilege['portal_id']])) {
					$privileges[$user_privilege['portal_id']] = array();
				}

				if($modules = CTable('privilege_scope')->select_all(array('privilege_id'=>$user_privilege['privilege_id']))) {
					foreach($modules as $module) {
						$privileges[$user_privilege['portal_id']][$module['module']] = bindec($module['can_admin'].
							$module['can_developer'].$module['can_moderator'].
							$module['can_delete'].$module['can_edit'].
							$module['can_add'].$module['can_view_detail'].
							$module['can_view']);
					}
				}
			}
		}
		if($user_groups = CTable('user_group')->select_all(array('user_id'=>$user_id))) {
			foreach($user_groups as $user_group) {
				if(isset($user_group['group_id']) and $group = CTable('user')->select(array('id'=>$user_group['group_id']))) {
					if(!$group['privileges']) {
						$group_all_privileges = array();
						$group_privileges = CUser::privilege_cache($user_group['group_id'], $group_all_privileges);
					} else {
						eval('$group_all_privileges = '.$group['privileges'].';');
						eval('$group_privileges = '.$group['privilege_cache'].';');
					}
					$privileges = CString::array_merge($group_privileges, $privileges);
					$all_privileges = CString::array_merge($group_all_privileges, $all_privileges);
				}
			}
		}
		return var_export($privileges,1);
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $user_id
	 * @return unknown
	 */
	static function update_cache($user_id) {
		if($user_id) {
			$record = array('privilege_cache'=>CUser::privilege_cache($user_id,$all_privileges), 'privileges'=>var_export($all_privileges,1));
			CTable('user')->update($record, $user_id);
			return $record;
		}
	}

	/**
	 * Enter description here...
	 *
	 */
	static function flush_privilege_cache() {
		CTable('user')->update(array('privilege_cache'=>'', 'privileges'=>''), false);
		//xoa het cache user
		if(portal()->setting('export-user')) {
			CFile('publish/'.CPortal::$default.'/user')->delete();
		}
	}

	/**
	 * Enter description here...
	 *
	 */
	function save_privilege_cache() {
		$table = CTable('privilege')->change_store(CXmlStore('users/admin.xml', '/root/'));
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $status
	 * @param unknown_type $module
	 */
	function update_online_status($status = 1, $module = false) {
		return;
		if($this->is_login()) {
			$table = CTable('user_online');

			if($status == 0) {
				$table->delete($this->id);
			} else {
				$chat_windows = 0;
				if(CPortal::$default == 'kultech') {
					$chat_windows = session('chat_windows');
				}
				if($table->select($this->id)) {
					$table->update(array('id'=>$this->id,
						'time'=>time(),
						'time_out'=>time()+5*60,
						'module'=>$module?$module:module()->name,
						'chat_windows' => $chat_windows,
						'is_seller' => (isset($this->is_register_salesman) and $this->is_register_salesman == 2)?1:0,
						// Khoanb Edit 06.05.2009
						'estore_id'	=> (request('portal', 'kultech') == 'estore')?CEstore::getInstance()->get('id'):0,
					),$this->id);
				} else {
					$table->save(array(
						'id'=>$this->id,
						'time'=>time(),
						'time_out'=>time()+15*60,
						'module'=>$module?$module:module()->name,
						'chat_windows' => $chat_windows,
						'seller_point'=>$this->seller_point,
						'buyer_point'=>$this->buyer_point,
						'avatar'=>$this->avatar_url,
						'blast'=>$this->blast,
						'is_seller' => (isset($this->is_register_salesman) and $this->is_register_salesman == 2)?1:0,
						// Khoanb Edit 06.05.2009
						'estore_id'	=> (request('portal', 'kultech') == 'estore')?CEstore::getInstance()->get('id'):0,
					),$this->id);
				}
			}
			session('last_online_time',time());
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $privilege
	 * @return unknown
	 */
	function has_privilege($privilege) {
		return $this->is_admin() or (isset($this->privileges[portal()->id]) and isset($this->privileges[portal()->id][$privilege]));
	}

	function recache() {
		if ($user_id = $this->id) {
			$session = CSession::getInstance();
			$session->set('user', null);
			CUser::$current = new CUser($user_id);
			$sessInfo = null;
			$session->sessionInfo($sessInfo);
			$session->sessionWrite(session_id(), null);
		}
	}

	function logout() {
		if(CPortal::$default == 'kultech') {
			$this->update_online_status(0);
		}
		$this->ReportSaleActivity();
		session('user_id','');
		cookie('userId','');
		cookie('user_name','');
		cookie('saved_password','');
		cookie('shopping-cart-total-items',0);
		session_destroy();
	}

	function ReportSaleActivity() {
		if ($this->is_register_salesman && isset($this->start_time)) {
			require_once(ROOT_DIR.'/lib/models/CSalesActivity.php');
			new CSalesActivity($this->id, null, time()-$this->start_time, 0, 0, $this->start_time);
		}
	}
}

/**
 * Get current user
 *
 * @return unknown
 */
function &user() {
	return CUser::$current;
}
